import * as step from '@flow-step/step-toolkit';
import fs from 'fs';
import https from 'https';
import path from 'path';

export async function installKubectlSae() {
    let toolName: string = 'kubectl-sae'
    step.info(`Start to install kubectl-sae`)

    const toolUrl = `https://kubectl-sae-cn-beijing.oss-cn-beijing.aliyuncs.com/${toolName}`
    const destdir = `/usr/local/bin`
    const destFile = path.join(destdir, `${toolName}`);
    
    // download kubectl-sae
    const downloadFile = (url: string, dest: string): Promise<void> => {
        return new Promise((resolve, reject) => {
            const file = fs.createWriteStream(dest);
            https.get(url, (response) => {
                if (response.statusCode !== 200) {
                    reject(new Error(`Failed to get '${url}' (${response.statusCode})`));
                    return;
                }
                response.pipe(file);
                file.on('finish', () => {
                    file.close(() => resolve());
                });
            }).on('error', (err) => {
                fs.unlink(dest, () => reject(err));
            });
        });
    };

    try {
        await downloadFile(toolUrl, destFile);
        fs.chmodSync(destFile, 0o755);
        step.info(`Successfully installed ${toolName}`);
    } catch (error) {
        step.error(`Error installing ${toolName}: ${error}`);
        throw error;
    }

    return
}